import request from '@/util/request'
import type { TraceRecord } from '@/types/traceability'

// 溯源数据API接口
export const traceabilityApi = {
  // 获取所有溯源数据
  getAllTraceData: () => {
    return request.get<{
      code: number
      message: string
      data: TraceRecord[]
    }>('/blocktest/traceability/all')
  },

  // 根据产品ID获取溯源数据
  getTraceDataByProductId: (productId: string) => {
    return request.get<{
      code: number
      message: string
      data: TraceRecord[]
    }>(`/blocktest/traceability/product/${productId}`)
  },

  // 根据批次号获取溯源数据
  getTraceDataByBatchNo: (batchNo: string) => {
    return request.get<{
      code: number
      message: string
      data: TraceRecord[]
    }>(`/blocktest/traceability/batch/${batchNo}`)
  },

  // 分页获取溯源数据
  getTraceDataByPage: (params: {
    page: number
    pageSize: number
    productId?: string
    processType?: string
    status?: string
    startDate?: string
    endDate?: string
  }) => {
    return request.get<{
      code: number
      message: string
      data: {
        list: TraceRecord[]
        total: number
        page: number
        pageSize: number
      }
    }>('/blocktest/traceability/page', { params })
  },

  // 获取溯源统计数据
  getTraceStatistics: () => {
    return request.get<{
      code: number
      message: string
      data: {
        totalBatches: number
        qualifiedRate: number
        pendingIssues: number
        processTypeStats: {
          [key: string]: number
        }
        statusStats: {
          [key: string]: number
        }
      }
    }>('/blocktest/traceability/statistics')
  },

  // 添加溯源记录
  addTraceRecord: (data: Omit<TraceRecord, 'id' | 'blockchainHash' | 'blockHeight'>) => {
    return request.post<{
      code: number
      message: string
      data: TraceRecord
    }>('/blocktest/traceability/add', data)
  },

  // 更新溯源记录
  updateTraceRecord: (id: string, data: Partial<TraceRecord>) => {
    return request.put<{
      code: number
      message: string
      data: TraceRecord
    }>(`/blocktest/traceability/update/${id}`, data)
  },

  // 删除溯源记录
  deleteTraceRecord: (id: string) => {
    return request.delete<{
      code: number
      message: string
    }>(`/blocktest/traceability/delete/${id}`)
  },

  // 导出溯源数据
  exportTraceData: (params: {
    productId?: string
    processType?: string
    status?: string
    startDate?: string
    endDate?: string
    format: 'excel' | 'pdf' | 'csv'
  }) => {
    return request.get('/blocktest/traceability/export', { 
      params,
      responseType: 'blob'
    })
  }
} 